<template>
  <el-container style="height: 100%">
    <el-header>
      <h1>Neusoft&nbsp;&nbsp;东软体检报告管理系统</h1>
      <p>医生：{{ doctorRealName }}</p>
    </el-header>
    <el-container>
      <el-aside width="260px">
        <el-descriptions class="margin-top" title="预约客户信息" :column="1" border>
          <el-descriptions-item>
            <template #label>
              <div class="cell-item">预约编号</div>
            </template>
            {{ orders.orderId }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>
              <div class="cell-item">手机号码</div>
            </template>
            {{ orders.userId }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>
              <div class="cell-item">真实姓名</div>
            </template>
            {{ orders.users.realName }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>
              <div class="cell-item">性别</div>
            </template>
            {{ orders.users.sex == 1 ? "男" : "女" }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>
              <div class="cell-item">套餐类型</div>
            </template>
            {{ orders.setmeal.name }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>
              <div class="cell-item">体检日期</div>
            </template>
            {{ orders.orderDate }}
          </el-descriptions-item>
        </el-descriptions>
        <el-button type="primary" style="margin-top: 20px" @click="toOrdersList">查询体检用户</el-button>
      </el-aside>
      <el-main>
        <div class="main-box">
          <el-collapse>
            <el-collapse-item :title="ci.ciName" v-for="(ci, ciIndex) in ciReportArr" :key="ci.ciId">
              <el-row style="color: #888">
                <el-col :span="12" style="box-sizing: border-box; padding: 6px 10px"
                  v-for="(cidr, cidrIndex) in ci.cidrList" :key="cidr.ciId">
                  <span style="
                      background-color: #ba634e;
                      color: #fff;
                      box-sizing: border-box;
                      padding: 1px 3px;
                      border-radius: 3px;
                      margin-right: 5px;
                    " v-if="cidr.iserror == 1">异</span>

                  <span style="margin-right: 5px; vertical-align: top">{{
                    cidr.name
                  }}</span>

                  <el-input style="width: 26%; margin-right: 2px" size="small" :placeholder="cidr.name"
                    v-if="cidr.type != 4" v-model="ciReportArr[ciIndex].cidrList[cidrIndex].value"
                    @blur="cidrCheckByBlur(ciIndex, cidrIndex)" />
                  <el-input style="width: 80%" type="textarea" :rows="2" :placeholder="cidr.name"
                    v-model="ciReportArr[ciIndex].cidrList[cidrIndex].value" v-if="cidr.type == 4" />

                  <span style="margin-right: 15px">{{ cidr.unit }}</span>

                  <span v-if="cidr.normalvaluestring">正常值范围: {{ cidr.normalvaluestring }}</span>
                </el-col>
              </el-row>
              <el-button type="primary" style="margin-top: 8px" @click="updateCiDetailedReport(ciIndex)"
                v-if="orders.state == 1">{{ ci.ciName }}项保存</el-button>
            </el-collapse-item>
          </el-collapse>

          <el-card class="box-card" style="margin-top: 20px">
            <template #header>
              <div class="card-header">
                <span>总检结论</span>
                <el-button class="button" type="danger" @click="updateOrdersState"
                  v-if="orders.state == 1">体检套餐总检结果报告归档</el-button>
              </div>
            </template>
            <div>
              <el-table :data="overallResultArr" style="width: 100%">
                <el-table-column prop="orid" label="编号" width="60" />
                <el-table-column prop="title" label="总检结论项标题" width="180" />
                <el-table-column prop="content" label="总检结论项内容" />
                <el-table-column label="操作" width="120">
                  <template #default="scope">
                    <el-button type="text" size="small" @click="toUpdateOverallResult(scope.row)"
                      v-if="orders.state == 1">更新</el-button>
                    <el-button type="text" size="small" @click="removeOverallResult(scope.row)"
                      v-if="orders.state == 1">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>

              <el-form ref="formRef" :model="overallResultForm" style="margin-top: 20px" label-width="120px"
                v-if="orders.state == 1">
                <el-form-item label="总检结论标题">
                  <el-input v-model="overallResultForm.title" placeholder="总检结论标题"></el-input>
                </el-form-item>
                <el-form-item label="总检结论内容">
                  <el-input v-model="overallResultForm.content" :rows="2" type="textarea"
                    placeholder="总检结论内容"></el-input>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="addOverallResult">添加</el-button>
                  <el-button type="warning" @click="resetOverallResult">清空</el-button>
                </el-form-item>
              </el-form>
            </div>
          </el-card>

          <!-- 总检结论更新用对话框 -->
          <el-dialog v-model="dialogVisible" title="总检结论项更新" width="60%">
            <span>
              <el-form :model="updateOverallResultForm" label-width="120px">
                <el-form-item label="总检结论标题">
                  <el-input v-model="updateOverallResultForm.title"></el-input>
                </el-form-item>
                <el-form-item label="总检结论内容">
                  <el-input v-model="updateOverallResultForm.content" type="textarea" :rows="3"></el-input>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="updateOverallResult">更新</el-button>
                  <el-button @click="dialogVisible = false">取消</el-button>
                </el-form-item>
              </el-form>
            </span>
          </el-dialog>
        </div>
      </el-main>
    </el-container>
  </el-container>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { useStore } from 'vuex';
import axios from '@/plugins/axios';


const router = useRouter();
const store = useStore();
const route = useRoute();

const orderId = ref(route.query.orderId);
const state = ref(route.query.state);
const phone = ref(route.query.phone);
const realName = ref(route.query.realName);
const sex = ref(route.query.sex);
const setmealName = ref(route.query.setmealName);
const hospitalName = ref(route.query.hospitalName);
const orderDate = ref(route.query.orderDate);

// 定义响应式变量并给 doctor 和 orders 对象设置默认值
const doctor = ref({ realname: '' });
const doctorRealName = computed(() => doctor.value.realname);

const orders = ref({
  orderId: '',
  userId: '',
  users: { realName: '', sex: 1 },
  setmeal: { name: '' },
  orderDate: '',
  state: 1
});
const ciReportArr = ref([]);
const overallResultArr = ref([]);
const overallResultForm = ref({
  orid: '',
  title: '',
  content: ''
});
const updateOverallResultForm = ref({
  orid: '',
  title: '',
  content: ''
});
const dialogVisible = ref(false);

// 加载数据
onMounted(() => {
  const doctorData = sessionStorage.getItem('doctor');
  if (doctorData) {
    try {
      doctor.value = JSON.parse(doctorData);
      console.log(doctor.value.realname);
    } catch (e) {
      console.error('Failed to parse doctor data:', e);
    }
  } else {
    console.error('No doctor data found in sessionStorage');
  }
  // 确保在元素挂载之后设置 orders 的值
  setTimeout(() => {
    orders.value = {
      orderId: orderId.value,
      userId: phone.value,
      users: { realName: realName.value, sex: sex.value },
      setmeal: { name: setmealName.value },
      orderDate: orderDate.value,
      state: state.value
    };
    ciReportArr.value = [
      {
        ciId: 1,
        ciName: '血常规',
        cidrList: [
          { ciId: 1, name: '白细胞', value: '', unit: '10^9/L', normalvaluestring: '4-10', iserror: 0, type: 1 },
          { ciId: 2, name: '红细胞', value: '', unit: '10^12/L', normalvaluestring: '4-5.5', iserror: 0, type: 1 }
        ]
      }
    ];
    overallResultArr.value = [
      { orid: '001', title: '血常规结论', content: '正常' }
    ];
  }, 0); // 延迟执行确保 DOM 已挂载
  queryOverallResult();
  fetchCiReports();
});

// 查询总检结论
const queryOverallResult = async () => {
  const respsonse = await axios.get(`http://localhost:9000/report/Overallresult?orderid=${orderId.value}`);
  if (respsonse.data.code == 200) {
    overallResultArr.value = respsonse.data.data;
  }
  else {
    alert(respsonse.data.message);
  }
}

// 查询体检报告项和项目明细
const fetchCiReports = async () => {
  const respsonse = await axios.get(`http://localhost:9000/cireport/getReportDetails?orderId=${orderId.value}`);
  if (respsonse.data.code == 200) {
    ciReportArr.value = respsonse.data.data;
  }
  else {
    alert(respsonse.data.message);
  }
}

// 查询体检用户
function toOrdersList() {
  router.push({ path: '/ordersList' });
}

// 检查输入值
function cidrCheckByBlur(ciIndex, cidrIndex) {
  let cidr = ciReportArr.value[ciIndex].cidrList[cidrIndex];
  cidr.iserror = cidr.value < parseFloat(cidr.normalvaluestring.split('-')[0]) || cidr.value > parseFloat(cidr.normalvaluestring.split('-')[1]) ? 1 : 0;
}

// 更新详细报告项
const updateCiDetailedReport = async (ciIndex) => {
  console.log(`更新详细报告项: ${ciReportArr.value[ciIndex].ciName}`);
  const ciReport = ciReportArr.value[ciIndex];
  if (ciReport && ciReport.cidrList) {
    ciReport.cidrList.forEach(cidr => {
      axios.post(`http://localhost:9000/cireport/updateReportDetails`, 
        `cidrid=${cidr.cidrid}&value=${cidr.value}`
      )
      .then(response => {
        if (response.data.code == 200) {
          console.log(`${ciReport.ciName}保存成功`);
          alert(response.data.message);
        } else {
          alert(response.data.message);
        }
      })
      .catch(error => {
        console.error(`Error updating ${ciReport.ciName}:`, error);
        alert(error);
      });
    });
  } else {
    console.error(`Invalid ciReport or cidrList for index ${ciIndex}`);
  }
};

// 更新总检结论
const updateOverallResult = async () => {
  const respsonse = await axios.post(`http://localhost:9000/report/updateOverallResult`,
    `orid=${updateOverallResultForm.value.orid}&title=${updateOverallResultForm.value.title}&content=${updateOverallResultForm.value.content}`);
  if (respsonse.data.code == 200) {
    alert(updateOverallResultForm.value.orid + respsonse.data.message)
  }
  else {
    alert(updateOverallResultForm.value.orid + respsonse.data.message)
  }
  // 再次请求总检结论
  queryOverallResult();
  console.log(`更新总检结论: ${updateOverallResultForm.value.title}`);
  dialogVisible.value = false;
}

// 添加总检结论
const addOverallResult = async () => {
  // overallResultArr.value.push({
  //   orid: new Date().getTime().toString(),
  //   title: overallResultForm.value.title,
  //   content: overallResultForm.value.content
  // });
  const respsonse = await axios.post(`http://localhost:9000/report/addOverallResult`,
    `orderid=${orderId.value}&title=${overallResultForm.value.title}&content=${overallResultForm.value.content}`);
  if (respsonse.data.code == 200) {
    alert(respsonse.data.message)
  }
  else {
    alert(respsonse.data.message)
  }
  // 再次请求总检结论
  queryOverallResult();
  overallResultForm.value.title = '';
  overallResultForm.value.content = '';
}

// 删除总检结论
const removeOverallResult = async (row) => {
  overallResultArr.value = overallResultArr.value.filter(item => item !== row);
  const respsonse = await axios.post(`http://localhost:9000/report/deleteOverallResult`,
    `orid=${row.orid}`);
  if (respsonse.data.code == 200) {
    alert(respsonse.data.message)
  }
  else {
    alert(respsonse.data.message)
  }
}

// 更新总检结论项
function toUpdateOverallResult(row) {
  updateOverallResultForm.value = { ...row };
  dialogVisible.value = true;
}

// 清空总检结论表单
function resetOverallResult() {
  overallResultForm.value.title = '';
  overallResultForm.value.content = '';
}

// 更新订单状态 将订单归档
const updateOrdersState = async () => {
  const respsonse = await axios.post(`http://localhost:9000/orders/archiveOrder`,
    `orderId=${orderId.value}&state=2`);
  if (respsonse.data.code == 200) {
    alert(respsonse.data.message)
  }
  else {
    alert(respsonse.data.message)
  }
  console.log('订单状态更新');
}
</script>




<style scoped>
.el-header {
  background-color: #b3c0d1;
  color: var(--el-text-color-primary);
  text-align: center;
  line-height: 60px;

  display: flex;
  align-items: center;
  justify-content: space-between;
  color: #1c51a3;
}

.el-header h1 {
  font-size: 22px;
  font-weight: 700;
}

.el-header p {
  font-size: 16px;
}

.el-aside {
  background-color: #d3dce6;
  box-sizing: border-box;
  padding: 20px;
}

.el-main {
  background-color: #e9eef3;
  padding: 0;
}

.el-main .main-box {
  width: 100%;
  height: 680px;
  overflow: auto;
  background-color: #fff;
  box-sizing: border-box;
  padding: 20px;
}

/*********** 描述列表 ***********/

.el-descriptions {
  margin-top: 20px;
}

.cell-item {
  display: flex;
  align-items: center;
}

.margin-top {
  margin-top: 20px;
}

/*********** 总检结论 ***********/
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.box-card {
  width: 100%;
}
</style>